package com.dianrui.qiyouriding.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.dianrui.qiyouriding.Constant;
import com.dianrui.qiyouriding.R;
import com.dianrui.qiyouriding.activity.AgreeMentActivity;
import com.dianrui.qiyouriding.activity.AgreementInfoActivity;
import com.dianrui.qiyouriding.activity.LoginActivity;
import com.dianrui.qiyouriding.adapter.AgreeListAdapter;
import com.dianrui.qiyouriding.bean.Agree;
import com.dianrui.qiyouriding.event.RfreshAgreement;
import com.dianrui.qiyouriding.event.RfreshAgreementList;
import com.dianrui.qiyouriding.okhttp.OkHttpRequest;
import com.dianrui.qiyouriding.util.SharedUtil;
import com.dianrui.qiyouriding.util.StringUtils;
import com.dianrui.qiyouriding.util.ToastUtil;
import com.dianrui.qiyouriding.util.Url;
import com.dianrui.qiyouriding.view.PulltoRefresh.PullToRefreshBase;
import com.dianrui.qiyouriding.view.PulltoRefresh.PullToRefreshListView;
import com.google.gson.JsonObject;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;


/**
 * 查看合同的list
 */
public class FragAgreement extends BaseFragment {
    private AgreeListAdapter agreeListAdapter;
    private int pageIndex = 1;
    private List<Agree> mAgreeList = new ArrayList<>();
    private boolean isPrepared;
    private int status;

    @BindView(R.id.agreement_listview)
    PullToRefreshListView agreementListview;
    @BindView(R.id.emptyView)
    LinearLayout emptyView;


    public static FragAgreement newInstance(String fragmentType, int position) {
        FragAgreement newFragment = new FragAgreement();
        Bundle bundle = new Bundle();
        bundle.putString("fragmentType", fragmentType);
        Log.e("FragmnetPosition", position + "");
        newFragment.setArguments(bundle);
        return newFragment;
    }


    @Override
    public int getContentViewId() {
        return R.layout.frag_agreement;
    }

    @Override
    public void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        agreeListAdapter = new AgreeListAdapter(getActivity(), mAgreeList);
        agreementListview.setAdapter(agreeListAdapter);
        agreeListAdapter.setOnAgreeClickListener(new AgreeListAdapter.AgreementClickListener() {
            @Override
            public void onAgreeClick(String contractId) {
                getActivity().startActivity(new Intent(getActivity(), AgreementInfoActivity.class).putExtra("contract_id", contractId));
            }
        });
        agreementListview.setMode(PullToRefreshBase.Mode.BOTH);
        agreementListview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                getAgreement(true);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageIndex++;
                getAgreement(false);

            }
        });
        isPrepared = true;

    }

    @Override
    public void getData() {
        getAgreement(true);
    }


    /**
     * 页面切换
     */
    @Subscribe
    public void onPageSelected(RfreshAgreement event) {
        if (event != null) {
            AgreeMentActivity.fragemntPosition = event.getType();
            status = event.getType();
            Log.e("fragemnt位置---->", AgreeMentActivity.fragemntPosition + "");
            if (!isPrepared) {
                getAgreement(true);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RfreshAgreementList rfreshAgreementList) {
        getAgreement(true);
    }

    private void getAgreement(final boolean isRfresh) {
        if (isRfresh) {
            pageIndex = 1;
        }
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("p", pageIndex);
        jsonObject.addProperty("status", status);
        OkHttpRequest.getInstance().postWithMemberToken(Url.CONTRACT, jsonObject.toString(),  new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    if (agreementListview != null) {
                        agreementListview.onRefreshComplete();
                    }
                    if (isRfresh) {
                        mAgreeList.clear();
                    }
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && isAdded()) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                JSONArray jsonArray = jsonObject.optJSONArray("data");
                                if (jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        Agree agree = new Agree();
                                        agree.contract_id = jsonArray.optJSONObject(i).optString("contract_id");
                                        agree.order_code = jsonArray.optJSONObject(i).optString("order_code");
                                        agree.money = jsonArray.optJSONObject(i).optString("money");
                                        agree.number = jsonArray.optJSONObject(i).optString("number");
                                        agree.create_time = jsonArray.optJSONObject(i).optString("create_time");
                                        agree.status = jsonArray.optJSONObject(i).optString("status");
                                        mAgreeList.add(agree);
                                    }
                                    if (agreeListAdapter != null) {
                                        agreeListAdapter.refresh(mAgreeList);
                                    }
                                }
                            } else if ("1001".equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                                SharedUtil.setToken("");
                                JumpKillActivitys(LoginActivity.class);
                                getActivity().finish();
                            }

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (mAgreeList.size() <= 0) {
                        emptyView.setVisibility(View.VISIBLE);
                        agreementListview.setVisibility(View.GONE);
                    } else {
                        emptyView.setVisibility(View.GONE);
                        agreementListview.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void failedRequest(String result) {

            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
